package by.hqsoftware.RollingBall.GraphicElements;

import javax.microedition.khronos.opengles.GL10;

import by.hqsoftware.RollingBall.Converter;

public class Ball extends Mesh{
	
	public Ball() {
		mPosition = new Point3df();
		mLastPosition = new Point3df();
	}

	private Field mField;	
	private Point3df mPosition;
	private Point3df mLastPosition;	
    private float mAccelerationX;
    private float mAccelerationY;           
           
    public void setField(Field field) {
    	mField = field;
    }
    
    /**
     * Compute ball's physics
     */
    public void computePhysics(float sensorX, float sensorY, float dT, float dTC) {

		
    	//assign mass
    	final float mass = 1f;
    	//calculate gravity
    	final float gravityX = -sensorX * mass;
    	final float gravityY = sensorY * mass;
    	
    	//F = mass * acceleration
    	//acceleration = F / mass;
    	
    	//calculate acceleration
    	final float aX = gravityX * 200;// * mGameView.metersToPixelsX;
    	final float aY = gravityY * 200;// * mGameView.metersToPixelsY; 
    	    	
    	
		//calculate new position
		final float x = (float)(mPosition.x + (mPosition.x - mLastPosition.x) * dTC + mAccelerationX * Math.pow(dT, 2));
		final float y = (float)(mPosition.y + (mPosition.y - mLastPosition.y) * dTC + mAccelerationY * Math.pow(dT, 2));				
		
		Point3df testPoint = new Point3df(x, y, 0.0f);
		if (!mField.isPointInsideField(testPoint)) {					
			mPosition = mField.getClosestPointOnCircle(testPoint);
		} else {
			mPosition.x = x;
			mPosition.y = y;
		}
		
		ry += (mLastPosition.x - mPosition.x) / 3.14f * 360;
		rx += (mLastPosition.y - mPosition.y) / 3.14f * 360;		
		
		//save position
		mLastPosition.x = mPosition.x;
		mLastPosition.y = mPosition.y;    	
		
		//save accelerations
		mAccelerationX = aX;
		mAccelerationY = aY;
				
    }	

    @Override
    public void draw(GL10 gl) {
    	x = mPosition.x;
    	y = mPosition.y;    	    	
    	super.draw(gl);
    }
	
	@Override
	protected void customDraw(GL10 gl) {
		
		final float ambientAndDiffuse[] = {0.0f, 0.1f, 0.9f, 1.0f};
	    gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_AMBIENT_AND_DIFFUSE, Converter.toBuffer(ambientAndDiffuse));
	    
	    final float specular[] = {0.3f, 0.3f, 0.3f, 1.0f};
	    gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_SPECULAR, Converter.toBuffer(specular));
	    gl.glMaterialf(GL10.GL_FRONT_AND_BACK, GL10.GL_SHININESS, 25.0f);
	    
	    final float emission[] = {0.1f, 0.2f, 0.2f, 0.3f};
	    gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_EMISSION, Converter.toBuffer(emission));		
	}
	
}
